﻿using System.Net.WebSockets;
using System.Text;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace WebSocketClient;

[ObservableObject]
public partial class MainPageViewModel {
    [ObservableProperty] private string _input;

    [ObservableProperty] private string _output;

    private ClientWebSocket ws;

    [RelayCommand]
    private async Task ConnectAsync() {
        ws = new ClientWebSocket();
        await ws.ConnectAsync(new Uri("ws://localhost:5139/ws"), default);
    }

    [RelayCommand]
    private async Task SendAsync() {
        var inputBytes = Encoding.Default.GetBytes(Input);

        await ws.SendAsync(new ArraySegment<byte>(inputBytes),
            WebSocketMessageType.Text, WebSocketMessageFlags.EndOfMessage,
            default);

        var buffer = new byte[1024 * 4];
        var receiveResult =
            await ws.ReceiveAsync(new ArraySegment<byte>(buffer),
                CancellationToken.None);
        Output = Encoding.Default.GetString(buffer);
    }
}